{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 一个入门级的 LangChain 例子，包含 LLM 调用、提示词使用、LCEL 操作、LLM 输出后的内容格式化。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##  import 需要的函数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "from langchain.schema import(\n",
    "    AIMessage,HumanMessage,SystemMessage\n",
    ")\n",
    "\n",
    "from langchain.prompts.chat import(\n",
    "    ChatPromptTemplate,SystemMessagePromptTemplate,\n",
    "    HumanMessagePromptTemplate\n",
    ")\n",
    "\n",
    "from dotenv import load_dotenv, find_dotenv"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 从配置文件获取 OpenAI 密钥"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "_ = load_dotenv(find_dotenv())\n",
    "\n",
    "# 配置 OpenAI 服务\n",
    "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')  ## 设置openai的key\n",
    "OPENAI_API_BASE = os.getenv('OPENAI_BASE_URL')  ## 更换为代理地址\n",
    "# print(os.getenv(\"OPENAI_API_KEY\"))\n",
    "# print(os.getenv(\"OPENAI_BASE_URL\"))\n",
    "llm = ChatOpenAI(openai_api_base=OPENAI_API_BASE, openai_api_key=OPENAI_API_KEY,\n",
    "                  temperature=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 简单的与 LLM 交互"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "\n",
    "messages = [\n",
    "    SystemMessage(content=\"你是一位恋爱顾问。\"),\n",
    "    HumanMessage(content=\"我的女朋友今天心情不好，我该怎么哄她开心呢？\"),\n",
    "]\n",
    "\n",
    "llm.invoke(messages)\n",
    "\n",
    "\n",
    "result = llm.invoke(messages)\n",
    "print(result.content)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 提示词中有变量"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "template=\"你是一位恋爱顾问，帮助人们写情书。情书的开头是'{letter_opening}'，需要表达'{emotion}'\"\n",
    "system_message_prompt=SystemMessagePromptTemplate.from_template(template)\n",
    "\n",
    "human_template=\"{user_text}\"\n",
    "human_template_prompt=HumanMessagePromptTemplate.from_template(human_template)\n",
    "\n",
    "prompt = chat_prompt=ChatPromptTemplate.from_messages([\n",
    "    system_message_prompt,\n",
    "    human_template_prompt\n",
    "])\n",
    "\n",
    "# 格式化并输出模板\n",
    "formatted_prompt = prompt.format_messages(letter_opening=\"亲爱的\", emotion=\"深深的爱意\", user_text=\"我想写一封让她感动的情书\")\n",
    "\n",
    "print(formatted_prompt)\n",
    "result = llm.invoke(formatted_prompt)\n",
    "print(result.content)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 输出格式化，以及 LCEL 用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_core.output_parsers import StrOutputParser\n",
    "\n",
    "template=\"你是一位恋爱顾问，帮助人们写情书。情书的开头是'{letter_opening}'，需要表达'{emotion}'\"\n",
    "system_message_prompt=SystemMessagePromptTemplate.from_template(template)\n",
    "\n",
    "human_template=\"{user_text}\"\n",
    "human_template_prompt=HumanMessagePromptTemplate.from_template(human_template)\n",
    "\n",
    "prompt = chat_prompt=ChatPromptTemplate.from_messages([\n",
    "    system_message_prompt,\n",
    "    human_template_prompt\n",
    "])\n",
    "\n",
    "\n",
    "chain = prompt | llm | StrOutputParser()\n",
    "result = chain.invoke({\"letter_opening\":\"亲爱的\", \"emotion\":\"深深的爱意\", \"user_text\":\"我想写一封让她感动的情书\"})\n",
    "print(result)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
